//
//  BaseGesturePOPView.m
//  MarryBackEnd
//
//  Created by mac on 2020/8/6.
//  Copyright © 2020 WPP. All rights reserved.
//

#import "BaseGesturePOPView.h"
@interface BaseGesturePOPView ()<UIScrollViewDelegate,UIGestureRecognizerDelegate>
@property(nonatomic,weak)UIControl *bgControl;
//@property(nonatomic,strong)UIPanGestureRecognizer *pan;
@property(nonatomic,assign)BOOL isDragScrollView;
@property(nonatomic,assign)CGFloat lastDrapDistance;
@property(nonatomic,strong)NSMutableArray<NSNumber *> *distanceArray;
@property(nonatomic,assign)CGFloat limitValue;
@property(nonatomic,assign)CGFloat originTop;
@end

@implementation BaseGesturePOPView
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self baseCreateProperty];
        [self baseCreateUI];
        [self startAnimation];
        [self addPanGesture];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame withParentView:(UIView *)parentView
{
    if (self = [self initWithFrame:frame]) {
        [parentView addSubview:self.bgControl];
    }
    return self;
}
- (void)dealloc
{
    NSLog(@"BaseGesturePOPView ---dealloc");
}
- (void)baseCreateProperty
{
    //自身
    self.backgroundColor = WhiteColor;
    self.frame = CGRectMake(0, HEIGHT, WIDTH, self.height);
    //其他
    self.animationDuration = 0.2;
    self.isDragScrollView = NO;
    self.lastDrapDistance = 0.0f;
    self.limitValue = self.height * 0.5;
    self.originTop = HEIGHT - self.height;
}
- (void)baseCreateUI
{
    [self.bgControl addSubview:self];
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(10*ADAPTER_WIDTH,10*ADAPTER_WIDTH)];
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.frame = self.bounds;
    layer.path = path.CGPath;
    self.layer.mask = layer;
}
#pragma mark - click
- (void)dismiss
{
    [self endAnimation];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((self.animationDuration + 0.01) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
        }];
        [self.bgControl.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
        }];
        [self.bgControl removeFromSuperview];
    });
}
#pragma mark - 动画
- (void)startAnimation
{
    WK(weakSelf)
    [UIView animateWithDuration:self.animationDuration animations:^{
        self.frame = CGRectMake(0, weakSelf.originTop, WIDTH, self.height);
    } completion:^(BOOL finished) {
        
    }];
}
- (void)endAnimation
{
    [UIView animateWithDuration:self.animationDuration animations:^{
        self.frame = CGRectMake(0, HEIGHT, WIDTH, self.height);
    } completion:^(BOOL finished) {
        
    }];
}
#pragma mark - 添加手势
- (void)addPanGesture
{
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panTargetSelector:)];
    [self addGestureRecognizer:pan];
    pan.delegate = self;
    self.pan = pan;
}
- (void)panTargetSelector:(UIPanGestureRecognizer *)ges
{
    /**
     translationInView:该方法返回在横坐标上、纵坐标上拖动了多少像素
     velocityInView：在指定坐标系统中pan gesture拖动的速度
     向下拉动 y 为正数 向上拉动 y 为负数 因为手势传递 所以mainView滑动距离
     */
    CGPoint point = [ges translationInView:self];
    //NSLog(@"point:%@,isDragScrollView:%d",NSStringFromCGPoint(point),self.isDragScrollView);
    if (self.isDragScrollView) {
        if (self.mainView.contentOffset.y <= 0) {
            if (point.y > 0) {
                //向下拖拽
                self.mainView.contentOffset = CGPointMake(0, 0);
                self.top = _originTop + point.y;
                //NSLog(@"向下拖拽");
                self.mainView.panGestureRecognizer.enabled = NO;
                self.mainView.panGestureRecognizer.enabled = YES;
                self.isDragScrollView = NO;
            } else {
                //向上拖拽
                //NSLog(@"向上拖拽");
                
            }
        } else {
            //让视图自己向上滑动
            //NSLog(@"111");
        }
    } else {
        if (point.y > 0) {
            self.top = _originTop + point.y;
        }
    }
    if (ges.state == UIGestureRecognizerStateEnded) {
        //NSLog(@"end:%f %d",point.y,self.isDragScrollView);
        //NSLog(@"end:%f %f",point.y,self.lastDrapDistance);
        //NSLog(@"%@",self.distanceArray);
        if (self.distanceArray.count > 2) {
            CGFloat lastValue = self.distanceArray.lastObject.floatValue;
            CGFloat lastValue1 = self.distanceArray[self.distanceArray.count - 2].floatValue;
            //轻扫手势 _mainView 是因为有的时候不需要调用mainView的
            if ((lastValue - lastValue1) > 10 && _mainView.contentOffset.y <= 0 ) {
                [self dismiss];
            } else {
                if (point.y > self.limitValue) {
                    [self dismiss];
                } else {
                    [self startAnimation];
                }
            }
        } else {
            if (point.y > self.limitValue) {
                [self dismiss];
            } else {
                [self startAnimation];
            }
        }
        [self.distanceArray removeAllObjects];
    }
    [self.distanceArray addObject:[NSNumber numberWithFloat:point.y]];
    //NSLog(@"%f %f",point.y,self.lastDrapDistance);
    self.lastDrapDistance = point.y;
    
    /**
     为什么搞数组呢？
     lastDrapDistance 在UIGestureRecognizerStateEnded里面和point.y一样的
     */
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    if(gestureRecognizer == self.pan) {
        if ([otherGestureRecognizer isKindOfClass:NSClassFromString(@"UIScrollViewPanGestureRecognizer")] || [otherGestureRecognizer isKindOfClass:NSClassFromString(@"UIPanGestureRecognizer")] ) {
            if([otherGestureRecognizer.view isKindOfClass:[UIScrollView class]] ) {
                return YES;
            }
        }
    }
    return NO;
}
//方法首先进来这里
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    //NSLog(@"shouldReceiveTouch--外层：%@",touch.view);
    if (gestureRecognizer == self.pan) {
        UIView *touchView = touch.view;
        while (touchView != nil) {
            //NSLog(@"shouldReceiveTouch内层：%@",touchView);
            if ([touchView isKindOfClass:[UIScrollView class]]) {
                self.isDragScrollView = YES;
                break;
            } else if (touchView == self) {
                self.isDragScrollView = NO;
            }
            touchView = (UIView *)[touchView nextResponder];
        }
    }
    return YES;
}
//方法然后进来这里 然后走pan手势监听
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer == self.pan) {
        //NSLog(@"gestureRecognizerShouldBegin");
    }
    return YES;
}
#pragma mark - lazy懒加载
- (UIControl *)bgControl
{
    if (!_bgControl) {
        UIControl *view = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
        [sharedKeyWindow addSubview:view];
        view.backgroundColor = rgba(0, 0, 0, 0.5);
        [view addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        _bgControl = view;
    }
    return _bgControl;
}
- (UIScrollView *)mainView
{
    if (!_mainView) {
        UIScrollView *view = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 100, WIDTH, self.height - 100)];
        [self addSubview:view];
        view.backgroundColor = WhiteColor;
        view.delegate = self;
        _mainView = view;
    }
    return _mainView;
}
- (NSMutableArray *)distanceArray
{
    if (!_distanceArray) {
        _distanceArray = [NSMutableArray array];
    }
    return _distanceArray;
}
@end

